package com.clusterswisdom.horn.api.ioc.api;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Element;

import com.clusterswisdom.horn.api.quartz.ScheduleContext;

public class ApiServiceConfig {
	
	private String channel;

	private String service;
	
	private Map<String, ApiConfig> configs = new HashMap<String, ApiConfig>();
	
	public ApiServiceConfig(String channel, Element root) {
		this.channel = channel;
		parse(root);
	}

	public String getChannel() {
		return channel;
	}

	public String getService() {
		return service;
	}
	
	public ApiConfig getApiConfig(String api) {
		return configs.get(api);
	}

	private void parse(Element root) {
		service = root.attributeValue("name");
		
		Iterator<?> apiIterator = root.elementIterator("api");
		while (apiIterator.hasNext()) {
			Element apiElement = (Element)apiIterator.next();
			ApiConfig apiConfig = new ApiConfig(this, apiElement);
			if (apiConfig.getCron() != null && apiConfig.getCron().trim().length() > 0) {
				ScheduleContext.getContext().addTaskAction(apiConfig);
				
			} else {
				configs.put(apiConfig.getName(), apiConfig);
				
			}
			
		}
	}
}
